package pers.lx.crm.service.market.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.lx.crm.base.common.pigeon.Result;
import pers.lx.crm.base.constant.ErrorConstant;
import pers.lx.crm.base.util.ResultUtil;
import pers.lx.crm.dao.business.BusinessDao;
import pers.lx.crm.dao.market.MarketDao;
import pers.lx.crm.dao.market.MarketInfoDao;
import pers.lx.crm.entiy.business.BusinessFlowDO;
import pers.lx.crm.entiy.market.MarketDO;
import pers.lx.crm.entiy.market.MarketInfoDO;
import pers.lx.crm.service.market.MarketService;

import java.util.List;

/**
 * Created by lxl on 2017/3/8.
 */
@Service
public class MarketServiceImpl implements MarketService {

    @Autowired
    private MarketDao marketDao ;

    @Autowired
    private MarketInfoDao marketInfoDao ;

    @Autowired
    private BusinessDao businessDao ;

    @Override
    public Result getMarkets(MarketDO marketDO) {
        Result result = new Result();
        try {
            marketDO.setList(marketDao.selectCustomerBusinessListPage(marketDO));
            return ResultUtil.getPageResult(marketDO,result) ;
        } catch (Exception e){
            e.printStackTrace();
            result.setError(ErrorConstant.UNKNOWN_ERROR);
        }
        return result;
    }

    @Transactional
    @Override
    public Result addMarket(MarketDO marketDO) {
        Result result = new Result() ;
        marketDao.insertCustomerBusiness(marketDO);
        List<BusinessFlowDO> businessFlowDOs = businessDao.selectBusinessFlow(marketDO.getBusinessId()) ;
        for (BusinessFlowDO businessFlowDO:businessFlowDOs){
            MarketInfoDO marketInfoDO = new MarketInfoDO() ;
            marketInfoDO.setCustomerBusinessId(marketDO.getId());
            marketInfoDO.setBusinessFlowId(businessFlowDO.getId());
            marketInfoDao.insertMarketInfo(marketInfoDO);
        }
        return result;
    }

    @Transactional
    @Override
    public Result removeMarkets(List<MarketDO> marketDOs) {
        Result result = new Result() ;
        for (MarketDO marketDO:marketDOs){
            marketInfoDao.deleteMarketInfo(marketDO);
            marketDao.deleteCustomerBusiness(marketDO);
        }
        return result;
    }

    @Override
    public Result getMarketInfos(int customerBusinessId) {
        Result result = new Result() ;
        result.addParam("marketInfos",marketInfoDao.selectMarketInfo(customerBusinessId));
        return result;
    }

    @Override
    public Result updateMarketInfo(List<MarketInfoDO> marketInfoDOs) {
        Result result = new Result() ;
        for (MarketInfoDO marketInfoDO:marketInfoDOs){
            marketInfoDao.updateMarketInfo(marketInfoDO);
        }
        return result;
    }
}
